home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7272 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  89 lines

  1. Path: erinews.ericsson.se!usenet
  2. From: Otmar Conradus <ETM.ETMCOOT@MEMO.ERICSSON.SE>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: A simple "find the bug" (please! I need help :)
  5. Date: Thu, 22 Feb 1996 10:48:55 -0800
  6. Organization: Ericsson
  7. Message-ID: <312CBA97.32BF@MEMO.ERICSSON.SE>
  8. References: <4gdr6n$6p0@guava.epix.net>
  9. NNTP-Posting-Host: etmpc905.etm.ericsson.se
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (Win16; I)
  14.  
  15. Jon wrote:
  16. > I wrote this just now and it's telling me that when i try to cout the
  17. > result at the bottom, it is an undefined value even though I did return
  18. > the result var...  See if you can help.
  19. > #include <iostream.h>
  20. > float num1;
  21. > float num2;
  22. > getnums () {
  23. > float result = num1 +num2;
  24. > cout << "What number?\n";
  25. > cin >> num1;
  26. > cout << "And?\n";
  27. > cin >> num2;
  28. > return result;
  29. > }
  30. > main (){
  31. > getnums ();
  32. > cout << result;
  33. > }
  34. >         ^^^^^^ right there is the result i want printed but it does not
  35. > recognize it even though I did try to return the value in the function
  36. > getnums... am I missing something?
  37. > Jon
  38.  
  39.  
  40. 1. You are using 2 global variables num1 and num2 but you didn't declare
  41.    a variable result.
  42.  
  43. 2. If you want your function getnums to return a value you must declare it
  44.    as:
  45.    float getnums()
  46.    and in your main procedure call it as:
  47.    result = getnums();
  48.  
  49. 3. So your whole program can look like this:
  50. #include <iostream.h>
  51.  
  52.  
  53. float getnums () {
  54.  float num1;    // abstain from using global variables if you
  55.  float num2;    // don't need them globally
  56.  float result;  // result is only known in this procedure
  57.  
  58.  cout << "What number?\n";   // read num1 and num2
  59.  cin >> num1;
  60.  cout << "And?\n";
  61.  cin >> num2;
  62.  
  63.  result = num1 + num2;        // calculate result
  64.  
  65.  return result;
  66.  }
  67.  
  68.  main (){
  69.  float result;  // result in only known in main
  70.  result = getnums();
  71.  cout << result;
  72.  }
  73.  
  74.  
  75. Otmar Conradus
  76. i24697@stuhi.ptf.hwb.nl
  77.